package com.litong.modules.face.recognize.demo;

import java.awt.Insets;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

import com.litong.modules.face.recognize.utils.FaceUtils;
import com.litong.modules.face.recognize.utils.MatImageUtils;
import com.litong.utils.dll.LibraryUtil;

public class Sample02OfFaceDetections {

  public static void main(String[] args) {
    LibraryUtil.addLibary();
    // 加载库文件
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    faceDetection();
  }

  private static void faceDetection() {
    // 获取摄像头视频流
    VideoCapture capture = new VideoCapture(0);
    // 如果没有打开摄像头,退出
    int height = (int) capture.get(Videoio.CAP_PROP_FRAME_HEIGHT);
    int width = (int) capture.get(Videoio.CAP_PROP_FRAME_WIDTH);
    if (height == 0 || width == 0) {
      System.out.println("camera not found! exit");
      System.exit(0);
    }

    // 实例化视频帧容器
    MatPanel panel = new MatPanel();
    // 创建jframe,并添加pannel到jfram
    JFrame frame = new JFrame("camera");
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.setContentPane(panel);
    frame.setVisible(true);
    Insets insets = frame.getInsets();
    // 设置宽带和高度
    frame.setSize(width + insets.left + insets.right, height + insets.top + insets.bottom);

    Mat mat = new Mat();
    while (frame.isShowing()) {
      // 获取视频帧
      capture.read(mat);
      // 检测人脸
      mat = detectFace(mat);
      // 转为图像显示
      BufferedImage image = MatImageUtils.mat2BufferImage(mat);
      panel.setBufferedImage(image);
      // repaint自动调用paint
      panel.repaint();
    }
    capture.release();
    frame.dispose();
  }

  /**
   * opencv实现人脸识别，同时检测到人脸和人眼时才截图
   */
  public static Mat detectFace(Mat mat) {
    // 创建2个人脸检测模型,faceDetector和eyeDetector,检测人脸和眼睛
    String openCVDir = "D:\\dev_program\\opencv-4.1.1";
    String frontalfaceAltXml = openCVDir + "\\sources\\data\\haarcascades\\haarcascade_frontalface_alt.xml";
    String eyeXml = openCVDir + "\\sources\\data\\haarcascades\\haarcascade_eye.xml";
    CascadeClassifier faceDetector = new CascadeClassifier(frontalfaceAltXml);
    CascadeClassifier eyeDetector = new CascadeClassifier(eyeXml);
    FaceUtils.detectFace(mat, faceDetector, eyeDetector);
    return mat;
  }
}